<?php

namespace control;
class aiCodeGenerateClass extends adIndexClass
{
    private const page    = 'aiCodeGenerate'; # 权限
    private const table   = 'aa_ai_order'; # 数据表
    private const tableMx = 'aa_ai_order_detail'; # 数据表
    private const title   = 'AI物联码生成器';

    /*列表页-查询条件*/
    public function home()
    {
        $html =
            text(["name" => "orderNo", "title" => "供应商编码"]) .
            text(['name' => "name", "title" => "供应商名称",]);
        return $this->homeFun($this->search($html));
    }

    public function homeSearch(): bool|string
    {
        //全等查询数组
        $equal = array(
            'coid' => self::$coid,
        );
        // 获取查询结果
        $where = search(["=" => $equal]);
        $supplierWhere = " 1=1 ";
        if ($this->post('orderNo')) {
            $supplierWhere .= " and orderNo like '%{$this->post('orderNo')}%' ";
        }
        if ($this->post('name')) {
            $supplierWhere .= " and name like '%{$this->post('name')}%' ";
        }
        if ($this->post('orderNo') || $this->post('name')) {
            $supplierWhere = substr($supplierWhere, 4);
            $where .= " and supplierId in (select id from aa_supplier where $supplierWhere)";
        }
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        //
        $tr[] = [$checkAll, "供应商编码", "供应商名称", "生成AI物联码数量","创建时间"];
        //获取记录
        $url = root . "control/adIndex.php?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                //                'edit'   => array("title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'$array[id]'})"),
                'detail' => array("title" => "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $aa_supplier = query("aa_supplier", " id = '$array[supplierId]'");
            $tr[] = [$this->dominate($dominate), $aa_supplier['orderNo'], $aa_supplier['name'], $array['num'], $array['time']];
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('" . self::page . "', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     */
    public function edit(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(
            array(
                "table"   => array(
                    array(
                        "供应商：" => selectMultiple(['name' => "supplierId", "table" => "aa_supplier", 'sqlField' => 'name', 'sqlId' => 'id', "title" => "请填写"]),
                    ),
                    array(
                        "AI物联码生成数量：" => text(['name' => "num", "type" => "number", "title" => "请填写"]),
                    ),
                ),
                'formTwo' => 'listForm'
            )
        );
        //返回
        return $this->layer(array("title" => "设置", "height" => 200, "width" => 500, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?? self::getId();
        $field = [
            'supplierId' => $this->post('supplierId'),
            'num'        => $this->post('num'),
        ];
        $annotation = [
            'supplierId' => '供应商',
            'num'        => 'AI物联码生成数量',
        ];
        $rules = [
            'supplierId' => 'required',
            'num'        => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (empty($info['id'])) {
            $field = array_merge($field, [
                "id"         => $id,
                'coid'       => self::$coid,
                'createId'   => self::$stid,
                'updateTime' => $this->time,
                'time'       => $this->time
            ]);
            $json['warn'] = self::insert(["table" => self::table, "field" => $field]);
            // 查询当日最新的code
            $codeInfo = query(self::tableMx, " time like '%{$this->date}%' order by code desc");
            $code = $codeInfo['code'];
            $prefix = date('ymd');
            $temp = 1;
            if ($code) {
                $temp = intval(str_replace($prefix, '', $code)) + 1;
            }
            for ($i = $temp; $i < (int)$field['num'] + $temp; $i++) {

                self::insert(['table' => self::tableMx, "field" => [
                    "id"         => suiji(),
                    "orderId"    => $id,
                    "code"       => $prefix . (str_pad($i, 4, '0', STR_PAD_LEFT)),
                    'createId'   => self::$stid,
                    'updateTime' => $this->time,
                    'time'       => $this->time
                ]]);
            }
        } else {
            $json['warn'] = self::update(["table" => self::table, "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }
        if (in_array($json['warn'], array("新增成功", "更新成功"))) {
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = $this->control['name'] . $type . "了一个" . self::title . "：ID：" . $id;
            $this->logText(["type" => self::page, "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.php?cla=' . self::page . '&fun=home';
        }
        //返回
        resp:
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $id = $this->get('id');
        $info = query(self::table, " id = '$id'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            $button = [];
            if ($this->power(self::page, "del")) {
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            $checkAll = $this->checkAll("tableMxForm", "listId");
            $tr[] = [$checkAll, '序号', 'AI智能码'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by code "));
            foreach ($result['array'] as $index => $array) {
                $dominate = array(
                    "box" => array("name" => "listId", "value" => $array['id']),
                );
                $tr[] = [
                    $this->dominate($dominate),
                    $index + 1,
                    $array['code'],
                ];
            }
            $prinButton = "<span onclick=\"printEdit()\" class='spanButton'>批量打印</span>\n";
            $aa_supplier = query("aa_supplier", " id = '$info[supplierId]'");
            $data['html'] = $this->tableShow(array(
                "button"   => $button,
                array(
                    array(
                        "供应商名称"       => $aa_supplier['name'],
                        "AI物联码生成数量" => $info['num'],
                    ),
                ),
                '订单明细' => array(
                    array(
                        "<div>" . $prinButton . "</div>" .
                        "<form name='tableMxForm'>" . hidden(["name" => "parentId", "value" => $id]) .
                        $this->tableMany(array('tr' => $tr)) . "</form>",
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);//var hiprintTemplate2 = new hiprint.PrintTemplate({template:JSON.parse(jsonC)});,settingContainer: '#PrintElementOptionSetting'
            $html .= <<<eof
<script>
function printEdit() {
    // layer('aiCodeGenerate','printEdit',$("form[name='tableMxForm']").serialize())
    get_checked_box('aiCodeGenerate','printEdit','tableMxForm')
}

</script>
eof;

        }
        //返回
        return $html;
    }

    /********打印弹窗**************/
    public function printEdit(): bool|string
    {

        $root = root;
        $listArr = explode(',', $this->post('listId'));
        $content = '';
        foreach ($listArr as $id) {
            //材料信息
            $material_sku = query(self::tableMx, "id = '$id'");
            $barcode = $material_sku['code'];
            $parameter = urlencode(para("AICodeUrl") . "?code=" . $barcode);
            $content .= <<<efo
                            <li>
                               <div class="qr-content">
                                 <div class="qr-content-barcode">{$barcode}</div>
                                     <img alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
                                     <div style="font-size: 20px">打&nbsp;开&nbsp;蓝&nbsp;牙<br>微信扫一扫</div>
                                      <input name='listId[]' type='hidden' value='$id'>
                               </div>
                           </li>
efo;
        }
        $print = "打印";
        $html = <<<efo
                <form name="printForm" target="_blank" method="post" action="{$root}control/adIndex.html?cla=aiCodeGenerate&fun=printPage">
                <div class="printEditPage">
                      <ul>
                           {$content}
                      </ul>
                </div>
                
                <div style='width: 100%;margin-top: 40px;text-align: center;'>
                    <input type='submit' class='button' value='{$print}' ">
                </div>
                </form>

efo;

        return $this->layer(array("title" => "打印", "height" => 650, "width" => 900, "html" => $html . $this->style()));
    }

    /**
     * 样式
     */
    public function style(): string
    {
        return <<<efo
<style>
.printEditPage{width: 100%;height: 500px;overflow: auto;}
.printEditPage>ul>li{float: left;margin: 5px;padding: 5px}
.qr-content{width: auto;height: auto;background-color: #F0F8FA;text-align: center;margin:0;padding:0;overflow: auto}
.qr-content img{width: 120px}
.qr-content-barcode{font-size: 15px;font-weight: bold;margin:5px 0 0 0}
.qr-content-bottom{word-wrap:break-word;}
.qr-num{width: 250px;margin: 10px}
.page-num-simple{
display: none;
}
</style>
efo;
    }

    /**
     * 打印
     */
    public function printPage(): string
    {
        $idArr = $this->post('listId');
        $root = root;
        $content = '';
        $num=[];
        foreach ($idArr as $key=> $id) {
            //材料信息
            $material_sku = query(self::tableMx, "id = '$id'");
            $barcode = $material_sku['code'];
            $num[]=$barcode?$barcode:'不存在';
            $parameter = urlencode(para("AICodeUrl") . "?code=" . $barcode);
            $content .= <<<efo
                 <div class="qr-content num_{$key}">
                    <div class="qr-content-barcode">{$barcode}</div>
                      <img alt="" src='{$root}pay/wxpay/wxScanPng.php?url={$parameter}'>
                      <div style="font-size: 18px;line-height: 20px">打&nbsp;开&nbsp;蓝&nbsp;牙<br>微信扫一扫</div>
                 </div>
efo;
        }
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                        <div data-op-type='mix-box'>
                             <div class="nop-fill-box">
                              {$content}
                             </div>
                        </div>
                    </div>
                  
eof;
        $html .= $this->style();
        $html .= <<<efo
<style>
.qr-content{width: auto;height: 181px;margin: 0;overflow: hidden;background-color: white}
.qr-content img{width: 120px;}
.qr-content-bottom{font-size: 12px}
</style>
efo;

        $print = new printClass();
        return $print->showPrint( $html, 'portrait', ['padding' => "0mm", 'pageSizeOption' => ['width' => '33mm', 'height' => '49mm']]);
    }

    public function operate(): bool|string
    {
        $act = $this->post('act') ?? '';
        $pwd = $append = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = '是否确认删除所选数据?';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.php?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'append'   => $append,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * 删除
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                delete(array("table" => self::table, "where" => " id = '$id' "));
                delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.php?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}